package com.autoscript.web;

import com.autoscript.ISystemConstant;
import com.autoscript.exception.ASException;
import com.autoscript.service.ParameterCacheService;
import com.autoscript.service.PublicService;
import com.autoscript.service.UserService;
import com.autoscript.utils.SMSUtils;
import com.autoscript.utils.SessionMap;
import com.dfhc.util.ConvertHelper;
import com.dfhc.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信Controller
 * @author lsb
 * @version 1.0.0
 * @date 2021-02-02
 */
@RestController
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
@RequestMapping(value ="/api/sms")
public class SmsController {
    private static Logger logger= LoggerFactory.getLogger(SmsController.class);
    @Autowired
    private PublicService publicService;
    @Autowired
    private SessionMap sessionMap;
    /**
     * 发送短信验证码
     * @param request
     * @return
     */
    @RequestMapping(value = "sendSmsVerifyCode", produces = "application/json")
    @ResponseBody
    public Map<String, Object> sendSmsVerifyCode(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        //验证上次发送时间，防止发送过度频繁
        Map<String,Object> hSessionMap = sessionMap.get(request.getHeader(ISystemConstant.SESSION_ID));
        if(hSessionMap==null){
            logger.error("无效session！");
            result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
            result.put(ISystemConstant.AJAX_MESSAGE, "无效的Session");
            return result;
        }
        Instant sendTime = (Instant) hSessionMap.get(ISystemConstant.SMS_VALIDATE_CODE_SEND_TIME);
        ParameterCacheService parameterCacheService = ParameterCacheService.getSingleInstance();
        try {
            if (sendTime != null) {
                Instant now = Instant.now();
                String strSmsSendInterval="";
                try {
                    strSmsSendInterval = parameterCacheService.getString(ISystemConstant.CODE_DATA_SMS_SEND_INTERVAL);
                } catch (Exception e) {
                    throw new ASException(e.getMessage());
                }
                int smsSendInterval;
                try {
                    smsSendInterval = ConvertHelper.toInt(strSmsSendInterval);
                } catch (Exception e) {
                    logger.info("Convert to int fail!strSmsSendInterval:" + strSmsSendInterval);
                    smsSendInterval = 60;
                }
                logger.info("strSmsSendInterval:" + strSmsSendInterval);
                if (Duration.between(sendTime, now).getSeconds() < smsSendInterval)
                    throw new ASException("发送验证码过于频繁!");
            }
        }catch(ASException e){
            logger.error("发送短信验证码失败", e);
            result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
            result.put(ISystemConstant.AJAX_MESSAGE, e.getMessage());
            return result;
        }
        //获取手机号
        String mobilePhone = request.getParameter("mobilePhone");
        //产生四位随机数
        String validateCode = StringHelper.getRandStr(4);
          //发送短信
        //获取短信配置信息
        String cropId;
        String smsgatewayDomainUrl;
        String pwd;
        String contentTemp;
        String sendContent;
        String effectiveTime;
        try {
            cropId = parameterCacheService.getString(ISystemConstant.CODE_DATA_SMS_CROPID);
            pwd = parameterCacheService.getString(ISystemConstant.CODE_DATA_SMS_PWD);
            smsgatewayDomainUrl = parameterCacheService.getString(ISystemConstant.CODE_DATA_SMS_GATEWAY_DOMAIN_URL);
            contentTemp = parameterCacheService.getString(ISystemConstant.CODE_DATA_SMS_CONTENT_TEMP);
            System.out.println("contentTemp:"+contentTemp);
            effectiveTime = parameterCacheService.getString(ISystemConstant.CODE_DATA_SMS_EFFECTIVE_TIME);

            sendContent = String.format(contentTemp, validateCode,effectiveTime);
            SMSUtils.sendSMS(cropId, pwd, smsgatewayDomainUrl, mobilePhone, sendContent, "");


            result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
            result.put(ISystemConstant.AJAX_MESSAGE, "发送验证码成功");
            //设置验证码，发送时间到会话
            hSessionMap.put(ISystemConstant.SMS_VALIDATE_CODE, validateCode);
            hSessionMap.put(ISystemConstant.SMS_VALIDATE_CODE_SEND_TIME, Instant.now());
        }catch(Exception e) {
            logger.error("发送短信验证码失败", e);
            result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
            result.put(ISystemConstant.AJAX_MESSAGE, "发送验证码失败");
        }
        return result;
    }
}
